package com.hezuti.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.hezuti.common.structure.tree.TreeNode;


public class XmlUtil {
	private static final Logger logger;
	
	static {
		logger = Logger.getLogger(XmlUtil.class);
	}
	
	public XmlUtil() {
    	
    }
	
	public static TreeNode parse(Reader content) throws JDOMException, IOException {		
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(content);
		Element root = doc.getRootElement();
		
		return visit(root);
	}

	private static TreeNode visit(Element element) {
		//TreeNode root = new TreeNode(element.getName(), element.getText().trim());
		TreeNode root = new TreeNode(element.getName(), element.getText());
		logger.debug("element name: "+root.getName());
		logger.debug("element value: "+root.getValue());
		//visit attribute
		List attr = element.getAttributes();
		if(attr != null) {
			Iterator iterator = attr.iterator();
		    while(iterator.hasNext()) {
		         Attribute a = (Attribute) iterator.next();
		         TreeNode node = new TreeNode();
		         node.setName(a.getName());
		         node.setValue(a.getValue());
		         logger.debug("attribute name: "+node.getName());
		         logger.debug("attribute value: "+node.getValue());
		         root.addChild(node);
		    }
		}
		//visit children
		List content = element.getContent();
		Iterator iterator = content.iterator();
	    while(iterator.hasNext()) {
	         Object o = iterator.next();
	         if(o instanceof Element) {
	             Element child = (Element) o;
	             TreeNode node = visit(child);
	             root.addChild(node);
	         }
	    }
	    return root;
	}
	
	public static void main(String[] argv) {
		InputStream in = XmlUtil.class.getResourceAsStream("/product.xml");
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		try {
			TreeNode root = parse(reader);			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}